<?php

/**
 * Catalog super product configurable part block
 *
 * @category   Mage
 * @package    Mage_Catalog
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Xzsdsplus_Configurableplus_Block_Product_View_Type_Configurable extends Mage_Catalog_Block_Product_View_Type_Configurable {
    
    protected $_optionRenders = array();
    
    public function __construct() {
        parent::__construct();
        $this->addOptionRenderer(
            'default',
            'catalog/product_view_options_type_default',
            'catalog/product/view/options/type/default.phtml'
        );
        $this->addOptionRenderer(
            'select',
            'configurableplus/product_view_options_type_select',
            'catalog/product/view/options/type/select.phtml'
        );
    }
    
    /**
     * Composes configuration for js
     *
     * @return string
     */
    public function getDiamondJsonConfig() {
        
        $config = array();
        $attributes = array();
        $options    = array();
        $store      = $this->getCurrentStore();
        $taxHelper  = Mage::helper('tax');
        $currentProduct = $this->getProduct();

        $preconfiguredFlag = $currentProduct->hasPreconfiguredValues();
        if ($preconfiguredFlag) {
            $preconfiguredValues = $currentProduct->getPreconfiguredValues();
            $defaultValues       = array();
        }

        foreach ($this->getAllowProducts() as $product) {
            $productId  = $product->getId();
            foreach ($this->getAllowAttributes() as $attribute) {
                $productAttribute   = $attribute->getProductAttribute();
                $productAttributeId = $productAttribute->getId();
                $attributeValue     = $product->getData($productAttribute->getAttributeCode());
                if (!isset($options[$productAttributeId])) {
                    $options[$productAttributeId] = array();
                }

                if (!isset($options[$productAttributeId][$attributeValue])) {
                    $options[$productAttributeId][$attributeValue] = array();
                }
                $options[$productAttributeId][$attributeValue][] = $productId;
            }

            $product = Mage::getModel('catalog/product')->load($productId);
            foreach ($product->getOptions() as $option) {
                /* @var $option Mage_Catalog_Model_Product_Option */
                $priceValue = 0;
                if ($option->getGroupByType() == Mage_Catalog_Model_Product_Option::OPTION_GROUP_SELECT) {
                    $_tmpPriceValues = array();
                    foreach ($option->getValues() as $value) {
                        /* @var $value Mage_Catalog_Model_Product_Option_Value */
                       $_tmpPriceValues[$value->getId()] = Mage::helper('core')->currency($value->getPrice(true), false, false);
                    }
                    $priceValue = $_tmpPriceValues;
                } else {
                    $priceValue = Mage::helper('core')->currency($option->getPrice(true), false, false);
                }
                $config[$option->getId()] = $priceValue;
            }
            //return Mage::helper('core')->jsonEncode($config);
        }
        
        $this->_resPrices = array(
            $this->_preparePrice($currentProduct->getFinalPrice())
        );

        foreach ($this->getAllowAttributes() as $attribute) {
            $productAttribute = $attribute->getProductAttribute();
            $attributeId = $productAttribute->getId();
            $info = array(
               'id'        => $productAttribute->getId(),
               'code'      => $productAttribute->getAttributeCode(),
               'label'     => $attribute->getLabel(),
               'options'   => array()
            );

            $optionPrices = array();
            $prices = $attribute->getPrices();
            if (is_array($prices)) {
                foreach ($prices as $value) {
                    if(!$this->_validateAttributeValue($attributeId, $value, $options)) {
                        continue;
                    }
                    $currentProduct->setConfigurablePrice($this->_preparePrice($value['pricing_value'], $value['is_percent']));
                    Mage::dispatchEvent(
                        'catalog_product_type_configurable_price',
                        array('product' => $currentProduct)
                    );
                    $configurablePrice = $currentProduct->getConfigurablePrice();

                    $info['options'][] = array(
                        'id'        => $value['value_index'],
                        'label'     => $value['label'],
                        'price'     => $configurablePrice,
                        'oldPrice'  => $this->_preparePrice($value['pricing_value'], $value['is_percent']),
                        'products'  => isset($options[$attributeId][$value['value_index']]) ? $options[$attributeId][$value['value_index']] : array(),
                    );
                    $optionPrices[] = $configurablePrice;
                    //$this->_registerAdditionalJsPrice($value['pricing_value'], $value['is_percent']);
                }
            }
            /**
             * Prepare formated values for options choose
             */
            foreach ($optionPrices as $optionPrice) {
                foreach ($optionPrices as $additional) {
                    $this->_preparePrice(abs($additional-$optionPrice));
                }
            }
            if($this->_validateAttributeInfo($info)) {
               $attributes[$attributeId] = $info;
            }

            // Add attribute default value (if set)
            if ($preconfiguredFlag) {
                $configValue = $preconfiguredValues->getData('super_attribute/' . $attributeId);
                if ($configValue) {
                    $defaultValues[$attributeId] = $configValue;
                }
            }
        }

        $taxCalculation = Mage::getSingleton('tax/calculation');
        if (!$taxCalculation->getCustomer() && Mage::registry('current_customer')) {
            $taxCalculation->setCustomer(Mage::registry('current_customer'));
        }

        $_request = $taxCalculation->getRateRequest(false, false, false);
        $_request->setProductClassId($currentProduct->getTaxClassId());
        $defaultTax = $taxCalculation->getRate($_request);

        $_request = $taxCalculation->getRateRequest();
        $_request->setProductClassId($currentProduct->getTaxClassId());
        $currentTax = $taxCalculation->getRate($_request);

        $taxConfig = array(
            'includeTax'        => $taxHelper->priceIncludesTax(),
            'showIncludeTax'    => $taxHelper->displayPriceIncludingTax(),
            'showBothPrices'    => $taxHelper->displayBothPrices(),
            'defaultTax'        => $defaultTax,
            'currentTax'        => $currentTax,
            'inclTaxTitle'      => Mage::helper('catalog')->__('Incl. Tax')
        );

        $config = array(
            'attributes'        => $attributes,
            'template'          => str_replace('%s', '#{price}', $store->getCurrentCurrency()->getOutputFormat()),
//            'prices'          => $this->_prices,
            'basePrice'         => $this->_registerJsPrice($this->_convertPrice($currentProduct->getFinalPrice())),
            'oldPrice'          => $this->_registerJsPrice($this->_convertPrice($currentProduct->getPrice())),
            'productId'         => $currentProduct->getId(),
            'chooseText'        => Mage::helper('catalog')->__('-- Choose Carat Weight --'),
            'taxConfig'         => $taxConfig
        );

        if ($preconfiguredFlag && !empty($defaultValues)) {
            $config['defaultValues'] = $defaultValues;
        }

        $config = array_merge($config, $this->_getAdditionalConfig());

        return Mage::helper('core')->jsonEncode($config);
    }
    
    /**
     * Add option renderer to renderers array
     *
     * @param string $type
     * @param string $block
     * @param string $template
     * @return Mage_Catalog_Block_Product_View_Options
     */
    public function addOptionRenderer($type, $block, $template)
    {
        $this->_optionRenders[$type] = array(
            'block' => $block,
            'template' => $template,
            'renderer' => null
        );
        return $this;
    }
    
    /**
     * Get option render by given type
     *
     * @param string $type
     * @return array
     */
    public function getOptionRender($type) {
        
        if (isset($this->_optionRenders[$type])) {
            return $this->_optionRenders[$type];
        }

        return $this->_optionRenders['default'];
    }
    
    public function getGroupOfOption($type)
    {
        $group = Mage::getSingleton('catalog/product_option')->getGroupByType($type);

        return $group == '' ? 'default' : $group;
    }
    /**
     * Get option html block
     *
     * @param Mage_Catalog_Model_Product_Option $option
     */
    public function getOptionHtml(Mage_Catalog_Model_Product_Option $option, $product) {
        
        $renderer = $this->getOptionRender(
            $this->getGroupOfOption($option->getType())
        );

        if (is_null($renderer['renderer'])) {
            $renderer['renderer'] = $this->getLayout()->createBlock($renderer['block'])
                ->setTemplate($renderer['template']);
        }
        
        return $renderer['renderer']
            ->setProduct($product)
            ->setOption($option)
            ->toHtml();
    }
    
    public function getProductsOptions() {
        $html = '';
        foreach ($this->getAllowProducts() as $product) {
            $html .= '<div id="product_'.$product->getId().'" class="product_c_options"  style=" display: none; ">';
            $product = Mage::getModel('catalog/product')->load($product->getId());
            $_options = Mage::helper('core')->decorateArray($product->getOptions());
            foreach($_options as $_option){
                $html .=$this->getOptionHtml($_option, $product);
            }
            $html .= '</div>';
        }
        return $html;
    }
    
    public function getAttributeJsonConfig() {

        $config = array();
        $options    = array();

        foreach ($this->getAllowProducts() as $product) {
            $productId  = $product->getId();
            $product = Mage::getModel('catalog/product')->load($productId);
            foreach ($product->getOptions() as $option) {
                /* @var $option Mage_Catalog_Model_Product_Option */
                $priceValue = 0;
                if ($option->getGroupByType() == Mage_Catalog_Model_Product_Option::OPTION_GROUP_SELECT) {
                    $_tmpPriceValues = array();
                    foreach ($option->getValues() as $value) {
                        /* @var $value Mage_Catalog_Model_Product_Option_Value */
                        //$_tmpPriceValues[$value->getId()] = Mage::helper('core')->currency($value->getPrice(true), false, false);
                        // Add fixed price or percentage (don't calculate percentage yet, done by JS live instead)
                        $_tmpPriceValues[$value->getId()]['pricing_value'] = ($value->getPriceType() != 'percent') ? Mage::helper('core')->currency($value->getPrice(true), false, false) : $value->getPrice();
                        $_tmpPriceValues[$value->getId()]['is_percentage'] = ($value->getPriceType() == 'percent');
                    }
                    $priceValue = $_tmpPriceValues;
                } else {
                    $priceValue = Mage::helper('core')->currency($option->getPrice(true), false, false);
                }
                $config[$option->getId()] = $priceValue;
            }
        }
        return Mage::helper('core')->jsonEncode($config);
    }
}
